package minidb.file;
 
import static minidb.type.Const.*;

public class Page {

	private java.nio.ByteBuffer contents = java.nio.ByteBuffer.allocateDirect(PAGE_SIZE);
	private int pageNum;

	public Page(int pageNum){
		this.pageNum = pageNum;
	}
	
	public synchronized int pageNum(){
		return this.pageNum;
	}
	
	public synchronized int nextPage(){
		int next = contents.getInt(0);
		if(next!=0){
			write();
			this.pageNum = next;
			read();
		}
		return next;
	}
	
	public synchronized void pageNum(int pageNum){
		this.pageNum = pageNum;
	}
	
	public synchronized void read() {
		dbFile.read(pageNum, contents);
	}

	public synchronized void write() {
		dbFile.write(pageNum, contents);
	}

	public synchronized void append() {
		pageNum = dbFile.allocPage();
	}

	public synchronized int getInt(int offset) {
		contents.position(offset);
		return contents.getInt();
	}

	public synchronized void putInt(int offset, int val) {
		contents.position(offset);
		contents.putInt(val);
	}

	public synchronized String getString(int offset) {
		contents.position(offset);
		int len = (int)contents.get();
		if(len==0)
			return "";
		byte[] byteval = new byte[len];
		contents.get(byteval);
		return new String(byteval);
	}

	public synchronized void getByte(int position, java.nio.ByteBuffer record, int slot){
		byte []bt = new byte[slot];
		contents.position(position);
		contents.get(bt, 0, slot);
		record.rewind();
		record.put(bt, 0, slot);
	}
	
	public synchronized void putByte(int position, java.nio.ByteBuffer record, int slot){
		byte []bt = new byte[slot];
		record.position(0);
		record.get(bt);
		contents.position(position);
		contents.put(bt, 0, slot);
	}
	
	public synchronized void putString(int offset, String val) {
		contents.position(offset);
		contents.put((byte)val.length());
		if(val.length()==0)
			return;
		byte[] byteval = val.getBytes();
		contents.put(byteval);
	}
	
	public synchronized byte get(int pos){
		return contents.get(pos);
	}
	
	public synchronized void put(int pos, byte bt){
		contents.put(pos, bt);
	}
	
}
